<?php
/**
 * Created by PhpStorm.
 * User: 96151
 * Date: 2018/12/28
 * Time: 14:32
 */
namespace app\crontab\controller\sensors;

use app\common\model\article\PublishArticleModel;
use app\common\model\recommend\RecommendArticleEssenceModel;
use app\common\model\statistics\AppArticleClickDisplayLogModel;
use app\common\redis\ArticleCTRRedis;
use app\common\service\ElkLog;
use app\common\service\SensorsDataApiService;
use app\crontab\controller\CrontabCommon;

class Data extends CrontabCommon
{
    /**
     * 初始化方法
     */
    protected function _initialize()
    {
        //先执行父类初始化
        parent::_initialize();
    }

    /**
     * 拉取神策文章点击展示数据
     */
    public function get_app_article_click_display_data()
    {
        $SensorsDataApiService = new SensorsDataApiService();
        $data_list = $SensorsDataApiService->get_app_article_click_display_data();
        $add_list = array();

        foreach ( $data_list as $value ){
            $info = array(
                "user_id" => (int) $value['userid'],
                "article_id" => (int) $value['articleid'],
                'os_type'    => $value['$os'],
                'occurrence_time' => $value['time'],
                'client_sn'       => $value['client_sn'],
                'is_login'        => $value['is_login'],
                'operation_type'                => $value['operationtype']
            );
            $add_list[] = $info;
        }

        $AppArticleClickDisplayLogModel = AppArticleClickDisplayLogModel::getInstance();

        if ( $add_list ){
            $add_list_list = array_chunk( $add_list, 30 );
            foreach ( $add_list_list as $list ){
                var_dump($list);
                $res = $AppArticleClickDisplayLogModel->insertAll( $list );
                if ( !$res ){
                    ElkLog::write( array( 'message' => "SensorsDataApi_get_app_article_click_display_data_error" , "error" => $AppArticleClickDisplayLogModel->getError(), "data" => $add_list ) );
                }
            }
            echo "Success";
        }
    }

    /**
     * 定时清理程序
     */
    public function clear_app_article_log()
    {
        $AppArticleClickDisplayLogModel = AppArticleClickDisplayLogModel::getInstance();
        // 清理显示时间3天前的文章
        $where = array(
            'occurrence_time' => array( 'lt', date('Y-m-d H:i:s',time() - 86400 * 3 ) )
        );

        $res = $AppArticleClickDisplayLogModel->where( $where )->delete();
        echo $res;
    }

    /**
     * 计算文章CTR
     */
    public function calculation_ctr()
    {
        // 获取文章展示数大于50的文章
        $AppArticleClickDisplayLogModel = AppArticleClickDisplayLogModel::getInstance();

        // 获取两天内的文章点击展示数据
        $where = array(
            'occurrence_time' => array( 'gt', date('Y-m-d H:i:s', time() - 86400 * 3 ) )
        );

        $article_id_list = $AppArticleClickDisplayLogModel
            ->field( "article_id,COUNT( * ) AS count,operation_type" )
            ->where( $where )
            ->group( "article_id,operation_type,client_sn" )
            ->select();

        $article_id_list_format = array();

        foreach ( $article_id_list as $value ){
            $key = $value['article_id']."_".$value['operation_type'];
            if ( !isset( $article_id_list_format[ $key ] ) ){
                $article_id_list_format[ $key ] = array(
                    "article_id" => $value['article_id'],
                    "count"      => 0,
                    "operation_type" => $value['operation_type']
                );
            }

            $article_id_list_format[ $key ]["count"] ++;
        }

        // 组合数据
        $exposed_article_id_list = array();
        $click_article_id_list = array();

        if ( ENV == "test" ){
            $num = 10;
        } else {
            $num = 30;
        }

        // 处理数据
        foreach ( $article_id_list_format as $value ){
            if ( $value['operation_type'] == "exposed" ){
                if ( $value['count'] < $num ){
                    continue;
                }
                $exposed_article_id_list[$value['article_id']] = $value['count'];
            } else {
                $click_article_id_list[$value['article_id']] = $value['count'];
            }
        }

        $ArticleCTRRedis = ArticleCTRRedis::getInstance();
        $ArticleCTRRedis->Delete();

        $display_num = 100;

        $i = 0;
        // 计算文章CTR
        foreach ( $exposed_article_id_list as $key => $value ){

            // 若文章展示数大于100 则重新计算CTR
            if ( $value > $display_num ){
                $where = array(
                    'occurrence_time' => array( 'gt', date('Y-m-d H:i:s', time() - 86400 * 3 ) ),
                    'article_id'   => $key,
                    'operation_type' => 'exposed'
                );

                $client_list = $AppArticleClickDisplayLogModel->where( $where )->limit( $display_num )->group( "client_sn" )->order( "create_time desc" )->column( "client_sn" );

                $where = array(
                    'occurrence_time' => array( 'gt', date('Y-m-d H:i:s', time() - 86400 * 3 ) ),
                    'article_id'   => $key,
                    'operation_type' => 'click',
                    'client_sn' => array( 'in', $client_list )
                );

                echo "展示数：{$value}  点击数：{$click_article_id_list[$key]} ".PHP_EOL;

                $count_list = $AppArticleClickDisplayLogModel->where( $where )->group( "client_sn" )->column( "client_sn" );
                $exposed_article_id_list[ $key ] = $display_num;
                $click_article_id_list[$key] = count( $count_list );
                $value = $display_num;
                echo "展示数：{$value}  点击数：{$click_article_id_list[$key]} ".PHP_EOL;
                $i++;
            }

            // 若没有点击数据 则跳过数据计算
            if ( !isset( $click_article_id_list[$key]) ){
                continue;
            }

            $ctr = bcmul( bcdiv( $click_article_id_list[$key], $value, 4 ), 10000, 2 );
            echo "展示数：{$value}  点击数：{$click_article_id_list[$key]}    CTR：".$ctr.PHP_EOL;
            $ArticleCTRRedis->SortSetZadd( $key, $ctr );
        }

        // 计算优质库
        $this->format_essence();
        // 计算完成
    }


    /**
     * 根据CTR加入或移除优质库
     */
    public function format_essence()
    {
        $ArticleCTRRedis = ArticleCTRRedis::getInstance();
        $article_id_list = $ArticleCTRRedis->SortSetZRevRange(0, -1 ,true );

        $PublishArticleEssenceModel = RecommendArticleEssenceModel::getInstance();

        // 获取优质id列表
        $essence_article_id_list = $PublishArticleEssenceModel->get_key_value( "article_id", "id" );

        $essence_article_id_list = $essence_article_id_list ?: array();

        // 获取文章列表
        $PublishArticleModel = PublishArticleModel::getInstance();

        $article_list = $PublishArticleModel->muti_get_data_by_id_list( array_keys( $essence_article_id_list ), true,true,false );

        $time = time() - 86400;

        var_dump($article_id_list);
        // 检测CTR
        foreach ( $article_id_list as $key => $value ){
            // CTR大于10%自动加入优质库
            if ( $value >= 700 && !isset( $essence_article_id_list[$key] ) ){
                $add = array(
                    "article_id" => $key,
                    "type"       => "article",
                    "is_cms"     => 0
                );

                $PublishArticleEssenceModel->add_data( $add );
                echo "自动加入文章ID".$key."CTR{$value}".PHP_EOL;
            }

            // CTR小于8% 自动移除优质库
            if ( $value < 700 && isset( $essence_article_id_list[$key] ) ){
                $PublishArticleEssenceModel->delete_data_by_id( $essence_article_id_list[$key] );
                echo "自动移除文章ID".$key."CTR{$value}".PHP_EOL;
            }
        }

        echo "SUCCESS".PHP_EOL;


        // 移除一天时效性文章
        foreach ( $article_list as $value ){
            // 若文章的创建时间大于1并且已经过一天则移除优质库
            if ( strtotime( $value['create_time'] ) < $time && $value['is_time'] == 1 ){
                // 检测该文章是否为优质库后台添加
                $data = $PublishArticleEssenceModel->get_data_by_id( $value['id'] );
                if ( $data['is_cms'] == 1 ){
                    echo "检测为CMS后台添加文章取消移出".PHP_EOL;
                    continue;
                }
                $PublishArticleEssenceModel->delete_data_by_id( $essence_article_id_list[$value['id']] );
                echo "自动移除时效性文章ID".$value['id'].PHP_EOL;
            }
        }
    }


}